let _vue = null

export default class hashRouter {
    constructor (options){
        this.options = options
        this.routeMap = {}
        this.data = _vue.observable({
            current: '/'
        })
        location.hash = '#/'
    }

    static install(vue){
        if(hashRouter.install.installed) return
        hashRouter.install.installed = true

        _vue = vue

        // 给根vue挂载一个$router,$router存在vue根实例上
        _vue.mixin({
            beforeCreate() {
                if(this.$options.router){
                    _vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            },
        })
        
    }

    init(){
        this.initRouteMap()
        this.initComponent()
        this.initEvent()
        console.log(this.routeMap);
    }

    initRouteMap(){
        this.options.routes.forEach( async route => {
            let component = route.component
            if(component instanceof Promise){
                component = (await route.component).default
            }
            this.routeMap[route.path] = component
        });
    }

    initComponent(){
        _vue.component('router-link',{
            props:{
                to: String,
                tag: String,
            },
            render(h){
                return h(this.tag || 'a',{
                    href: this.to,
                    on:{
                        click:e=>{
                            e.preventDefault()
                            this.$router.data.current = this.to
                            location.hash = '#' + this.to
                        }
                    }
                },[this.$slots.default])
            }
        })

        _vue.component('router-view',{
             render(h){
                return h(this.$router.routeMap[this.$router.data.current])
            }
        })
    }

    initEvent(){
        window.addEventListener('hashchange',e=>{
            let url = new URL(e.newURL)
            this.data.current = url.hash.slice(1)
        })
    }
}